package com.thread.demo.communication;

public class ProducerConsumer {
    public static void main(String[] args) {
        PThread pThread = new PThread(new P("lock"));
        CThread cThread = new CThread(new C("lock"));
        pThread.start();
        cThread.start();
    }
}

class P {
    private String lock;

    public P(String lock) {
        this.lock = lock;
    }

    public void setValue() {
        try {
            synchronized (lock) {
                if (!ValueObject.value.equals("")) {
                    lock.wait();
                }
                System.out.println("生产者生产:");
                Thread.sleep(1000);
                ValueObject.value = "1";
                lock.notify();
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}


class PThread extends Thread {
    private P p;

    public PThread(P p) {
        this.p = p;
    }

    @Override
    public void run() {
        while (true) {
            p.setValue();
        }
    }
}

class C {
    private String lock;

    public C(String lock) {
        this.lock = lock;
    }

    public void getValue() {
        synchronized (lock) {
            if (ValueObject.value.equals("")) {
                try {
                    System.out.println("消费者等待");
                    lock.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            System.out.println("消费:" + ValueObject.value);
            ValueObject.value = "";
            lock.notify();
        }
    }

}

class CThread extends Thread {
    private C c;

    public CThread(C c) {
        this.c = c;
    }

    @Override
    public void run() {
        while (true) {
            c.getValue();
        }
    }
}

class ValueObject {
    public static String value = "";
}
